package org.umss.fixture.activities;

import java.util.ArrayList;
import java.util.List;

import org.umss.fixture.R;
import org.umss.fixture.services.FixtureBuilderServices;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

	private ListView listView;
	private List<String> championships;
	private static ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.listView);
		championships = new ArrayList<String>();
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,	long id) {
				Intent intent = new Intent(MainActivity.this.getBaseContext(), ShowPhasesActivity.class);
				intent.putExtra("CHAMPIONSHIP_NAME", championships.get(position));
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        startActivity(intent);
			}
		});

		new LoadChampionshipsTask().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.new_championship) {
			Intent a = new Intent(MainActivity.this.getBaseContext(), NewChampionshipActivity.class);
			a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(a);
		}
		return super.onOptionsItemSelected(item);
	}

	private class LoadChampionshipsTask extends AsyncTask<Void, Void, Void> {

		@Override
		public void onPreExecute() {
			if (progressDialog == null) {
				progressDialog = new ProgressDialog(MainActivity.this);
				progressDialog.setIndeterminate(true);
				progressDialog.setCancelable(false);
				progressDialog.setMessage("Retrieving championships...");
				progressDialog.show();
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			FixtureBuilderServices fixtureBuilderServices = new FixtureBuilderServices();
			championships = fixtureBuilderServices.getAvailableChampionships();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			listView.setAdapter(new ArrayAdapter<>(getBaseContext(),
					android.R.layout.simple_list_item_1, championships));

			if (progressDialog != null) {
				progressDialog.dismiss();
			}

			progressDialog = null;
		}
	}
}
